﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Furion;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using YBlog.Application.Contracts;

namespace YBlog.Application.System
{
    /// <summary>
    /// 初始化服务
    /// </summary>
    [ApiDescriptionSettings("System")]
    public class InitializeService : IBaseService
    {
        public InitializeService()
        {
        }

        public Task InitializeMemoryCache()
        {
            return Task.Run(async ()=> 
            {
                var controllers = App.EffectiveTypes.Where(e => e.GetInterface("IBaseService") != null);
                var effectiveActions = new Dictionary<MethodInfo, Type>();
                foreach (var controller in controllers)
                {
                    foreach (var action in controller.GetMethods())
                    {
                        if (action.GetCustomAttributes(true).Any(a => a is InitializationCacheAttribute))
                        {
                            effectiveActions.Add(action, controller);
                        }
                    }
                }
                foreach (var action in effectiveActions.Keys)
                {
                    var service = App.GetService(effectiveActions[action]);
                    var methodParams = action.GetParameters();
                    var invokeParams = new List<object>();

                    foreach (var param in methodParams)
                    {
                        invokeParams.Add(App.GetService(param.ParameterType));
                    }


                    await Task.FromResult(action.Invoke(service, invokeParams.ToArray()));
                }
            });
        }
    }
}
